<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <section class="todoapp">
    <hm-header @add-event="addEvent"></hm-header>
    <hm-main
      :list="showList"
      @clear-event="clearEvent"
      @remove-studens-event="removeStudens"
      @chenge-all-event="chengeAll"
    ></hm-main>
    <hm-footer
      :list="list"
      @remove-event="removeEvent"
      :stud="stud"
      @stud-all="stud = $event"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/completed": "done",
  "#/active": "undone",
};
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      list: JSON.parse(window.localStorage.getItem("list")) || [],
      stud: obj[location.hash]||'all',
    };
  },
  methods: {
    clearEvent(id) {
      // findIndex()找到符合条件的项的下标,并且返回第一个
      // 删除
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    // 添加中划线类名
    removeStudens(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.done = !obj.done;
    },
    // 头部输入框添加
    addEvent(name) {
      // 下标+1
      const id = this.list.length === 0 ? 1 : this.list.slice(-1)[0].id + 1;
      // 添加
      const obj = { id, name, done: false };
      this.list.push(obj);
    },
    // 全选
    chengeAll(value) {
      this.list = this.list.map((item) => {
        item.done = value;
        return item;
      });
    },
    removeEvent() {
      // false未完成
      this.list = this.list.filter((item) => item.done === false);
    },
  },
  computed: {
    showList() {
      // stud是all return全部
      if (this.stud === "all") {
        return this.list;
        // stud是done return已完成的
      } else if (this.stud === "done") {
        return this.list.filter((item) => item.done === true);
        // stud是done return未完成的
      } else {
        return this.list.filter((item) => item.done === false);
      }
    },
  },
  //深度监听
  watch: {
    handler(newValue) {
      window.localStorage.setItem("list", JSON.stringify(newValue));
    },
    deep: true,
  },
};
</script>

<style></style>
